<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :model="keyword" :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="getArticles">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="addHandler">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表v-loading="listLoading"-->
		<el-table border :data="tableDatas" v-loading="listLoading" @selection-change="handleSelectionChange"
				  :rowKey="getRowKey" highlight-current-row style="width: 100%;">
			<!--多选框-->
			<el-table-column type="selection" width="55" reserve-selection>
			</el-table-column>
			<el-table-column type="index" width="70" label="序号">
			</el-table-column>
			<el-table-column prop="articleName" label="文章名称" show-overflow-tooltip>
			</el-table-column>
			<el-table-column prop="articlePic" label="文章封面">
				<template scope="scope">
					<el-image :src="scope.row.articlePic" width="60px"></el-image>
				</template>
			</el-table-column>
			<el-table-column prop="articleTypeObj.typeName" label="文章类型" width="150">
			</el-table-column>
			<el-table-column prop="employee.username" label="作者">
			</el-table-column>
			<el-table-column prop="articleState" label="文章状态" sortable>
				<template scope="scope">
					<span v-if="scope.row.articleState == 0">草稿</span>
					<span v-else-if="scope.row.articleState == 1">发布</span>
					<span v-else>弃用</span>
				</template>
			</el-table-column>
			<el-table-column prop="articleReadCount" label="阅读量">
			</el-table-column>
			<el-table-column prop="articleStarNum" label="点赞量">
			</el-table-column>

			<el-table-column label="操作" align="center" fixed="right" width="300">
				<template scope="scope">
					<el-button size="small" @click="edit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="del(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" :disabled="this.sels.length === 0" @click="delBatch">批量删除</el-button>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
						   :page-sizes="[5, 10, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
						   :total="totals" style="float:right;">
			</el-pagination>
		</el-col>


		<!--新增界面-->
		<el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" ref="ruleForm" :rules="rules" status-icon>
				<el-form-item label="文章名称" prop="articleName">
					<el-input v-model="addForm.articleName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="文章封面" prop="articlePic">
					<el-upload class="upload-demo" action="http://localhost:8080/minio/upload" :on-success="handleSuccess"
							   :limit=1 :on-exceed="handleExceed" :on-remove="handleRemove" :file-list="fileList"
							   list-type="picture">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>
				</el-form-item>
				<el-form-item label="文章标签" prop="articleTag">
					<el-input v-model="addForm.articleTag" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="文章类型" prop="articleType">
					<el-cascader v-model="addForm.articleType" :options="articleTypeTree"
								 :props="{ checkStrictly: true, value: 'id', label: 'typeName' }" clearable></el-cascader>
				</el-form-item>
				<el-form-item label="文章状态" prop="articleState">
					<el-select v-model="addForm.articleState" filterable placeholder="请选择">
						<el-option v-for="item in articleStates" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="阅读量" prop="articleReadCount">
					<el-input v-model="addForm.articleReadCount" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="点赞量" prop="articleStarNum">
					<el-input v-model="addForm.articleStarNum" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="文章简介" prop="articleRemark">
					<quill-editor v-model="addForm.articleRemark" :options="editorOption">
					</quill-editor>
				</el-form-item>
				<el-form-item label="文章内容" prop="articleContent">
					<div class="edit_container">
						<quill-editor v-model="addForm.articleContent" :options="editorOption">
						</quill-editor>
					</div>
				</el-form-item>
				<el-form-item label="是否置顶" prop="topState">
					<el-switch active-value=1 inactive-value=0 v-model="addForm.topState" active-color="#13ce66"
							   inactive-color="#ff4949">
					</el-switch>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit()">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
// 工具栏配置
const toolbarOptions = [
	["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
	["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
	[{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
	[{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
	[{ script: "sub" }, { script: "super" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
	[{ indent: "-1" }, { indent: "+1" }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
	[{ direction: "rtl" }], // 文本方向-----[{'direction': 'rtl'}]
	[{ size: ["small", false, "large", "huge"] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
	[{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
	[{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
	[{ font: [] }], // 字体种类-----[{ font: [] }]
	[{ align: [] }], // 对齐方式-----[{ align: [] }]
	["clean"], // 清除文本格式-----['clean']
	["image", "link"] // 链接、图片、视频-----['link', 'image', 'video']
];

export default {
	components: {
		quillEditor
	},
	data() {
		return {
			// fileList: [],

			//富文本编辑器配置
			editorOption: {
				modules: {
					//工具栏定义的 
					toolbar: toolbarOptions
				},
				//主题
				theme: "snow",
				placeholder: "请开始书写您的博客内容..."
			},
			articleTypeTree: [],
			roles: [],
			articleStates: [
				{ "id": 0, "name": "草稿" },
				{ "id": 1, "name": "发布" },
				{ "id": 2, "name": "弃用" }
			], // 存储菜单的树数据
			row: "",
			title: "",
			sels: [], //存储多选记录
			addFormVisible: false,
			addForm: {
				id: null,
				articlePic: "",
				articleName: "",
				articleTag: "",
				articleType: null,
				articleState: null,
				topState: null,
				articleReadCount: null,
				articleStarNum: null,
				articleRemark: "",
				articleContent: ""
			},
			rules: {
				articleName: [
					{ required: true, message: '请输入文章名称', trigger: 'blur' },
				],
				articleTag: [
					{ required: true, message: '请输入文章标签', trigger: 'blur' }
				],
				articleType: [
					{ required: true, message: '请选择文章类型', trigger: 'change' },
				],
				articleState: [
					{ required: true, message: '请选择文章状态', trigger: 'change' }
				],
				articleReadCount: [
					{ required: true, message: '请指定阅读量', trigger: 'blur' }
				],
				articleStarNum: [
					{ required: true, message: '请指定点赞量', trigger: 'blur' }
				],
				articleRemark: [
					{ required: true, message: '请输入文章简介', trigger: 'blur' }
				],
				articleContent: [
					{ required: true, message: '请输入文章内容', trigger: 'blur' }
				]
			},
			listLoading: false,
			//查询对象

			keyword: null,
			totals: 0,//总记录条数
			currentPage: 1,//当前页,要传递到后台的
			pageSize: 5, //每页显示多少条
			tableDatas: [], //当前页数据
			fileUrl: "http://115.159.88.63:9090/java-very-good-0712/"
		}
	},
	methods: {
		handleExceed(files, fileList) {
			this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
		},

		handleRemove(file, fileList) {
			console.log(file, fileList);
			let fileArr = file.url.split("/")
			this.$http.delete("minio/" + fileArr[fileArr.length - 1])
				.then((result) => {
					if (result.data.success) {
						this.addForm.articlePic = '';
						this.$message.success(result.data.msg);
					} else {
						this.$message.error(result.data.msg);
					}

				})
		},
		handleSuccess(response, file, fileList) {
			let filePath = this.fileUrl + response.data;
			this.addForm.articlePic = filePath;
			this.$message.success("上传成功");

		},

		//表格多条数据选中事件
		handleSelectionChange(val) {
			/**
			 * val中存放的是所有已选择的行数据集合
			 */
			// console.log(val);
			this.sels = [];
			if (val != null && val.length > 0) {
				for (var i = 0; i < val.length; i++) {
					//往sels数组中存值
					this.sels.push(val[i].id);
				}
			}

			// if (val && val.length > 0) {
			// 	this.selectedWorkOrderList = val.map(e => e.securityId)
			// } else {
			// 	this.selectedWorkOrderList = []
			// }

		},
		// 获取每行的key，是唯一值就行，如果不唯一，一键全选会显示异常
		getRowKey(row) {
			return row.id
		},

		//提交新增表单数据
		addSubmit() {
			if (this.addForm.articleType) {
				this.addForm.articleType = this.addForm.articleType[this.addForm.articleType.length - 1];
			}
			//表单验证，统一验证
			this.$refs.ruleForm.validate((valid) => {
				if (valid) {
					if (!this.addForm.id) {
				this.$http.post("/article", this.addForm).then(result => {
					if (result.data.success) {
						this.$message({
							message: result.data.msg,
							type: 'success'
						});
						this.addFormVisible = false;
						this.getArticles();
					} else {
						this.$message({
							message: result.data.msg,
							type: 'error'
						});
					}
				});
			} else { // 修改
				this.addForm.createTime = null;
				this.$http.put("/article", this.addForm).then(result => {
					if (result.data.success) {
						this.$message({
							message: result.data.msg,
							type: 'success'
						});
						this.addFormVisible = false;
						this.getArticles();
					} else {
						this.$message({
							message: result.data.msg,
							type: 'error'
						});
					}
				});
			}
				} else {
					this.$message.error('提交失败，请输入数据');
					return false;
				}
			});
			// 新增
		

			

		},
		//点击编辑
		edit(row) {
			this.title = "修改"
			this.addFormVisible = true;//显示编辑框
			this.addForm = Object.assign({}, row);//回显数据
			this.addForm.articleType = this.menuEcho(this.articleTypeTree, this.addForm.articleType)
			if (this.addForm.articlePic) {
				this.fileList = [{ "url": this.addForm.articlePic }]
			}

		},
		//批量删除
		delBatch() {
			this.$confirm('确定删除这些数据吗？', '请确认', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$http.patch("/article/batchDel", this.sels).then(result => {
					if (result.data.success) {
						this.$message({
							type: 'success',
							message: result.data.msg
						});
						this.getArticles();
					} else {
						this.$message({
							type: 'error',
							message: result.data.msg
						});
					}
				});
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消操作'
				});
			});
		},

		//删除单条数据
		del(row) {
			this.$confirm('确定删除此条数据吗？', '请确认', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$http.delete("/article/" + row.id).then(result => {
					if (result.data.success) {
						this.$message({
							type: 'success',
							message: result.data.msg
						});

						// // 1.判断是否需要回到上一页
						// // 	第一个条件判断当前是否在最后一页
						// //  第二个条件判断总条数减去一条是否所在页为空
						// if (this.totals == totalPage && (this.totals - 1) % this.PageSize == 0 && this.currentPage > 1) {
						// 	this.currentPage = this.currentPage - 1;
						// }
						this.getArticles();
					} else {
						this.$message({
							type: 'error',
							message: result.data.msg
						});
					}
				});
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消操作'
				});
			});
		},
		addHandler() {
			this.fileList = []
			this.title = "新增"
			this.addForm = {
				id: null,
				articlePic: "",
				articleName: "",
				articleTag: "",
				articleType: null,
				articleState: null,
				topState: null,
				articleReadCount: null,
				articleStarNum: null,
				articleRemark: "",
				articleContent: ""
			};
			this.addFormVisible = true;
		},
		//选择第几页时触发
		handleCurrentChange(curentPage) {
			this.currentPage = curentPage;
			this.getArticles();
		},
		//选择每页显示记录条数
		handleSizeChange(pageSize) {
			this.curentPage = 1
			this.pageSize = pageSize
			this.getArticles();
		},
		handleChange(value) {
			console.log(this.addForm.courseTypeId);
		},
		//获取列表数据
		getArticles() {
			let para = {
				"currentPage": this.currentPage,
				"pageSize": this.pageSize,
				"keyword": this.keyword
			};
			this.listLoading = true; //显示加载圈
			//分页查询
			this.$http.post("/article/page", para).then(result => {
				console.log(result.data.data.total);
				console.log(result.data.data.list);

				this.totals = result.data.data.total;
				this.tableDatas = result.data.data.list;
				this.listLoading = false;  //关闭加载圈
			});
		},
		//获取列表数据
		getArticleTree() {
			this.$http.post("/articleType/tree").then(result => {
				this.articleTypeTree = result.data.data;

			});
		},
		// el-cascader递归获取父级id,list 数据列表,id 要查找的父级Id
		// list: 是级联选择器的options集合
		// id : 你要查找的级联关系的最后一级的id
		menuEcho(list, id) {
			let arr = []; // 在递归时操作的数组
			let returnArr = []; // 存放结果的数组
			let depth = 0; // 定义全局层级
			// 定义递归函数
			function childrenEach(childrenData, depthN) {
				for (var j = 0; j < childrenData.length; j++) {
					depth = depthN; // 将执行的层级赋值 到 全局层级
					arr[depthN] = childrenData[j].id;
					if (childrenData[j].id == id) {
						returnArr = arr.slice(0, depthN + 1); //将目前匹配的数组，截断并保存到结果数组，
						break;
					} else {
						if (childrenData[j].children) {
							depth++;
							childrenEach(childrenData[j].children, depth);
						}
					}
				}
				return returnArr;
			}

			return childrenEach(list, depth);
		},
	},
	mounted() {
		this.getArticles();
		this.getArticleTree();
	}
}

</script>

<style scoped></style>
